import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:wanxiang_app/bean/record_list_entity.dart';
import 'package:wanxiang_app/pages/my/charge.dart';
import 'package:wanxiang_app/utils/common.dart';
import '../../bean/collection_list_entity.dart';
import '../../utils/constant.dart';
import '../../utils/network_manager.dart';
import '../../utils/network_url.dart';
import '../../utils/toast_util.dart';
import '../../utils/user_util.dart';
import '../../widgets/money_textField.dart';
import '../../widgets/myappbar.dart';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:get/get.dart';

import '../home/detail.dart';

class RecordsController extends GetxController{

  @override
  void onInit() {
    super.onInit();
    _getService();
  }
  @override
  void onClose() {
    super.onClose();
  }
  List<CollectionListData> list = [];
  void _getService(){
    print('recordss||||==');
    String recordss = UserUtil.getRecord();
    print('recordss||||=='+recordss);
    if(recordss.isEmpty){
      list = [];
      return ;
    }

    List bbb = json.decode(recordss);
    String ccc = '';
    for(int i = 0;i<bbb.length;i++){
      ccc = ccc+bbb[i]['channelId']+'|'+bbb[i]['id'];
      if(i!=bbb.length-1){
        ccc = ccc+',';
      }
    }
    DioManager.getInstance().post(ServiceUrl.records,{
     "recordString": ccc
    }, (data) async {
      CollectionListEntity bannerEntity = CollectionListEntity.fromJson(jsonDecode(data));
      list = bannerEntity.data;
      list=  list.reversed.toList();
      update();
    }, (error) {
      ToastUtil.show(error);
    });
  }
  EasyRefreshController easyRefreshController = EasyRefreshController(
    controlFinishRefresh: false,
    controlFinishLoad: true,
  );
  var baopeiRate = 0.1.obs;

  _getBPFee(CollectionListData item){
    // double.parse(item.realityPrice)+20}元，包赔费用${().toStringAsFixed(2)
    double aa = (double.parse(item.sellPrice)) *baopeiRate.value;
    if(baopeiRate.value==0.1){
      if(aa<50){
        return 50;
      }
      return aa;
    }else {
      if(aa<100){
        return 100;
      }
      return aa;
    }


  }
}

class RecordsPage extends   GetView<RecordsController>  {

late RecordsController controller ;
late BuildContext context ;
@override
Widget build(BuildContext context1) {
  Get.lazyPut<RecordsController>(() => RecordsController());
  controller = Get.find();
  context = context1;

  return GetBuilder<RecordsController>(
    builder: (_){
      return  Scaffold(
          appBar: MyAppBar(context: context, title: '浏览记录',hasLeading: true,),
          backgroundColor: Colors.white,
          body:EasyRefresh(
            header: ClassicHeader(
              dragText: 'Pull to refresh'.tr,
              armedText: 'Release ready'.tr,
              readyText: 'Refreshing...'.tr,
              processingText: 'Refreshing...'.tr,
              processedText: 'Succeeded'.tr,
              noMoreText: 'No more'.tr,
              failedText: 'Failed'.tr,
              messageText: 'Last updated at %T'.tr,
            ),
            footer: ClassicFooter(
              dragText: 'Pull to load'.tr,
              armedText: 'Release ready'.tr,
              readyText: 'Loading...'.tr,
              processingText: 'Loading...'.tr,
              processedText: 'Succeeded'.tr,
              noMoreText: 'No more'.tr,
              failedText: 'Failed'.tr,
              messageText: 'Last updated at %T'.tr,
            ),
            controller: controller.easyRefreshController,
            onRefresh: () async {
              controller._getService();
            },
            onLoad: () async {
              controller.easyRefreshController.finishLoad(
                  IndicatorResult.noMore );
            },
            child: ListView.separated(
              itemBuilder: (context, index) {
                return _gameItems(controller.list[index]);
              }, separatorBuilder: (BuildContext context, int index) {
              return Container(height: 8.h,color: Color(0xFFF7F8FC),);
            }, itemCount: controller.list.length,
            ),
          ));
    },
  );

}



Widget _gameItems(CollectionListData item) {
  return InkWell(
      onTap: () {
        if(item.status == 0){
          ToastUtil.show('该商品已售罄');
          return;
        }
        Get.to(()=>DetailPage(),arguments: {
          "title":item.title,
          "record_id":item.channelId.toString(),
          "channel_name":item.channelName,
          "goods_id":item.id.toString(),
        },preventDuplicates:false);
      },
      child: Container(
        margin: EdgeInsets.only(left: 16.w, right: 13.w, top: 8.h),
        child: Column(
          children: [
            Row(
              children: [
                Container(
                    width: 120.w,
                    height: 88.h,
                    child: Stack(
                      children: [
                        ClipRRect(
                            borderRadius: BorderRadius.circular(10.r),
                            child: Image.network( item.imgUrl,fit: BoxFit.cover,width: 120.w,height: 88.h,)
                        ),
                        _officer(),
                      ],
                    )),
                SizedBox(
                  width: 8.w,
                ),
                Container(
                    width: MediaQuery.of(context).size.width -
                        29.w -
                        14.w -
                        120.w,
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          item.title,
                          style: TextStyle(
                            color: Color(0xFF333333),
                            fontSize: 14.sp,
                          ),
                          maxLines: 2,
                          textAlign: TextAlign.left,
                          overflow: TextOverflow.ellipsis,
                        ),
                        SizedBox(
                          height: 10.h,
                        ),
                        Text(
                          '区服：${item.categoryText}',
                          style: TextStyle(
                              color: Color(0xFF666666), fontSize: 13.sp),
                        ),
                        SizedBox(
                          height: 6.h,
                        ),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            _second(item.isMsg),
                            Row(
                              children: [
                                Text(
                                  '¥',
                                  style: TextStyle(
                                      color: Color(0xFFFF0000),
                                      fontSize: 12.sp),
                                ),
                                Text(
                                  item.sellPrice,
                                  style: TextStyle(
                                      color: Color(0xFFFF0000),
                                      fontSize: 18.sp),
                                ),
                              ],
                            )
                          ],
                        )
                      ],
                    ))
              ],
            ),
            SizedBox(
              height: 13.h,
            ),
            _info(item),

            item.status==1?
            _btn(item):Container()
          ],
        ),
      ));
}

Widget _second(ismsg) {
  return Container(
    width: 50.w,
    height: 20.h,
    alignment: Alignment.center,
    decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(8.r),
        border: Border.all(width: 1.w, color: Color(0xFF007BE5))),
    child: Text(
      '可二次',
      style: TextStyle(color: Color(0xFF007BE5), fontSize: 12.sp),
    ),
  );
}


  Widget _officer() {
    return Container(
      child: Image.asset(Constant.IMG_BASE+'baopei.png',width: 52.w,height: 17.h,fit: BoxFit.fitWidth,),
    );
  }


Widget _info(CollectionListData item) {
  return Container(
    color: Color(0xFFFBFBFB),
    padding: EdgeInsets.all(10.w),
    child: Column(
      children: [
        Row(
          children: [
            Flexible(
                flex: 1,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Row(
                      children: [
                        Text(
                          '游戏:',
                          style: TextStyle(
                              color: Color(0xFF666666), fontSize: 13.sp),
                        ),
                        Text(
                          item.subTitle,
                          style: TextStyle(
                              color: Color(0xFFFF9100), fontSize: 15.sp),
                        ),
                      ],
                    ),
                  ],
                )),
            Flexible(
              flex: 1,
              child: Text(
                '上架：${Common.transferDate2(item.addTime) }',
                style: TextStyle(color: Color(0xFF666666), fontSize: 13.sp),
              ),
            ),

            // Flexible(
            //   flex: 1,
            //   child: Text(
            //     '上架：2023.05.10  10:30',
            //     style: TextStyle(color: Color(0xFF666666), fontSize: 13.sp),
            //   ),
            // ),
          ],
        ),

        Row(
          children: [
            Flexible(
                flex: 1,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Row(
                      children: [
                        Text(
                          '状态:',
                          style: TextStyle(
                              color: Color(0xFF666666), fontSize: 13.sp),
                        ),

                        Text(
                          item.status==1? '在售':'已售罄',
                          style: TextStyle(
                              color: item.status==1?Color(0xFF00D841):Color(0xFF666666), fontSize: 13.sp),
                        ),
                        item.status==1?
                        Image.asset('${Constant.IMG_BASE}saling.png',width: 10.w,height: 10.w,):
                        Image.asset('${Constant.IMG_BASE}saled.png',width: 10.w,height: 10.w,)

                      ],
                    ),
                  ],
                )),
            Flexible(
              flex: 1,
              child: Text(
                '商品编号：${item.id}',
                style: TextStyle(color: Color(0xFF666666), fontSize: 13.sp),
              ),
            ),

            // Flexible(
            //   flex: 1,
            //   child: Text(
            //     '上架：2023.05.10  10:30',
            //     style: TextStyle(color: Color(0xFF666666), fontSize: 13.sp),
            //   ),
            // ),
          ],
        ),
        SizedBox(
          height: 7.h,
        ),
        // Row(
        //   children: [
        //     Expanded(
        //       flex: 1,
        //       child: Text(
        //         '商品类型:官方',
        //         style: TextStyle(color: Color(0xFF666666), fontSize: 13.sp),
        //       ),
        //     ),
        //     Expanded(
        //       flex: 1,
        //       child: Text(
        //         '营地号:asasasasa',
        //         style: TextStyle(color: Color(0xFF666666), fontSize: 13.sp),
        //       ),
        //     ),
        //   ],
        // ),
        // SizedBox(
        //   height: 7.h,
        // ),
        // Row(
        //   mainAxisAlignment: MainAxisAlignment.spaceBetween,
        //   children: [
        //     Text(
        //       '商品编号：${item.}',
        //       style: TextStyle(color: Color(0xFF666666), fontSize: 13.sp),
        //     ),
        //   ],
        // ),
      ],
    ),
  );
}

Future<Future<int?>> _showSingle(CollectionListData item) async {
  return showModalBottomSheet<int>(
      backgroundColor: Colors.transparent,
      isScrollControlled: true,
      context: context,
      builder: (BuildContext context1) {
        return AnimatedPadding(
            padding: MediaQuery.of(context1).viewInsets, // 我们可以根据这个获取需要的padding
            duration: const Duration(milliseconds: 100),
            child:  Container(
                height: 350.h,
                padding: EdgeInsets.all(16.w),
                clipBehavior: Clip.antiAlias,
                decoration: const BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.only(
                    topLeft: Radius.circular(20.0),
                    topRight: Radius.circular(20.0),
                  ),
                ),
                child: Column(
                  children: [
                    Text('选择包赔类型',style: TextStyle(
                        color: Color(0xFF333333),
                        fontSize: 15.sp
                    ),),
                    SizedBox(height: 15.h,),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Row(
                          children: [
                            Image.asset( '${Constant.IMG_BASE}item_new.png',width: 24.w,height: 17.h,),
                            Text('普通包赔10%',style: TextStyle(
                                color: Color(0xFF333333),
                                fontSize: 16.sp,
                                fontWeight: FontWeight.bold
                            ),)
                          ],
                        ),
                        Obx(() => InkWell(
                          onTap: (){
                            controller.baopeiRate.value = 0.1;
                            controller.update();
                          },
                          child:
                          controller.baopeiRate.value==0.1?
                          Image.asset( '${Constant.IMG_BASE}radio_yy.png',width: 18.w,height: 18.h,): Image.asset( '${Constant.IMG_BASE}icon_protect_n.png',width: 18.w,height: 18.h,),
                        )),


                      ],
                    ),
                    SizedBox(height: 10.h,),
                    Text('在下单购买账号时额外支付号价的10% (最低50元)，购买交易完成后，账号不转手 (换绑手机视为转手) 永久享受包赔服务，如出现账号找回情况，平台核实后在七天内进行处理，优先追回账号，超过七天未追回将全额退还支付号款，并对找回人员进行起诉追责处理!',
                      style: TextStyle(
                          color: Color(0xFF666666),
                          fontSize: 13.sp
                      ),),

                    SizedBox(height: 15.h,),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Row(
                          children: [
                            Image.asset( '${Constant.IMG_BASE}item_new.png',width: 24.w,height: 17.h,),
                            Text('2.5包赔20%',style: TextStyle(
                                color: Color(0xFF333333),
                                fontSize: 16.sp,
                                fontWeight: FontWeight.bold
                            ),)
                          ],
                        ),
                        Obx(() => InkWell(
                          onTap: (){
                            controller.baopeiRate.value = 0.2;
                            controller.update();
                          },
                          child:
                          controller.baopeiRate.value==0.2?
                          Image.asset( '${Constant.IMG_BASE}radio_yy.png',width: 18.w,height: 18.h,): Image.asset( '${Constant.IMG_BASE}icon_protect_n.png',width: 18.w,height: 18.h,),
                        )),


                      ],
                    ),
                    SizedBox(height: 10.h,),
                    Text('在下单购买账号时额外支付号价的20% (最低100元)，交易完成后，账号不转手 (换绑手机视为转手) 永久享受2.5倍包赔服务，如出现账号找回情况，平台核实后在七天内进行处理，优先追回账号，超过七天未追回将全额退还支付号款，并对找回人员进行起诉追责处理!',
                      style: TextStyle(
                          color: Color(0xFF666666),
                          fontSize: 13.sp
                      ),),
                    SizedBox(height: 10.h,),
                    Container(
                      width: Get.width,
                      color: Color(0x0D000000),
                      height: 1.h,
                    ),
                    Container(
                        alignment: Alignment.center,
                        height: 53.h,
                        child:    Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Obx(() => Text('号价为${ double.parse(item.sellPrice)}元，包赔费用${(controller._getBPFee(item)).toStringAsFixed(2)}元',style: TextStyle(
                                color: Color(0xFFFF0000),
                                fontSize: 14.sp
                            ),))
                            ,
                            InkWell(
                                onTap: (){
                                  double aa = double.parse(item.sellPrice) +controller._getBPFee(item);
                                  Get.to(()=>ChargePage(),arguments: {
                                    "user_name":UserUtil.getUSER()?.userName,
                                    "buy_type":"3",
                                    "channel_id":item.channelId.toString(),
                                    "goods_id":item.id.toString(),
                                    "price":aa.toStringAsFixed(2),
                                    "from":'buyNow',
                                    "readOnly":true,
                                    "CompensationCode":controller.baopeiRate.value==0.1?'ordinaryBP':'twoFiveBP',
                                  },preventDuplicates:false);


                                  // Get.off(()=>ChargePage(),arguments: {
                                  //   'readOnly':true,
                                  //   'price':aa.toStringAsFixed(2),
                                  //   'from':'buyNow',
                                  //   "channel_id":controller.detailData.channelId,
                                  //   "goods_id":controller.detailData.id.toString(),
                                  // });
                                },
                                child: Container(
                                  alignment: Alignment.center,
                                  width: 104.w,
                                  height: 31.h,
                                  decoration: BoxDecoration(
                                      color: Color(0xFF007BE5),
                                      borderRadius: BorderRadius.all(Radius.circular(16.r))
                                  ),
                                  child: Text('立即支付',style: TextStyle(
                                      color: Colors.white,
                                      fontSize: 13.sp
                                  ),),
                                )
                            )


                          ],
                        )
                    )

                  ],
                )
            )
        ) ;
      });
}
  Widget _btn(CollectionListData item){
    return InkWell(
      onTap: (){

        _showSingle(item);

        // Get.to(()=>ChargePage(),arguments: {
        //
        //   'readOnly':true,
        //   'price':item.sellPrice.toString(),
        //   'from':'buyNow',
        //   "channel_id":item.channelId.toString(),
        //   "goods_id":item.id.toString(),
        //
        // },preventDuplicates:false);
      },
      child:  Container(
          height: 36.h,
          margin: EdgeInsets.only(top: 1.h,bottom: 10.h),
          alignment: Alignment.center,
          decoration: BoxDecoration(
            color: Color(0xFF007BE5),
            borderRadius: BorderRadius.all(Radius.circular(20.r)),
          ),
          child: Text(
            '立即购买',style: TextStyle(
              fontSize: 13.sp,
              color: Colors.white
          ),
          )
      )
    );
  }
}